const jwt = require('jsonwebtoken');
class Token {
    static secret = "token_123456789"; //设置Token密钥    
    static options = {  //Token加密方式
        expiresIn: "1H" // 设置Token期限 过期时间 1day/H 60 ;"1d"  一天/小时 60秒     
    };

    //生成Token
    //payload : Token携带的信息
    static sign(payload) {
        //第三方库jwt--jsonwebtoken生成Token
        return jwt.sign(payload, this.secret, this.options);
    }

    static verify(token) {
        try {

            let decode = jwt.verify(token, this.secret);

            let { userId, userName } = decode;
            return {
                code: 1,
                msg: decode,
                data: { id: userId, name: userName }
            };

        } catch (error) {  //Token校验错误！
            let msg = "";
            switch (error.name) {
                case "TokenExpiredError":
                    msg = "Token过期，请重新登录";
                    break;

                default:
                    msg = "Token错误，请登录验证!";
                    break;
            }

            return {
                code: -1,
                msg: msg,
                data: {}
            };
        }
    }

    static getUser(req, res) {
        //验证用户Token
        const token = req.headers.authorization // 取到请求头中Token
        let result = Token.verify(token);
        if (result.code == 1) {
            let user = result.data;
            return user;
        }

        res.send({
            code: 401,
            msg: result.msg,
            data: {}
        });
        return null;
    }
}

module.exports = Token;  